package com.wyw.leetcode.learning.simple;

import com.wyw.leetcode.simple.parent.ListNode;

/**
 * leetcode topic 083
 *  删除排序链表中重复元素
 *      给定一个已排序的链表的头 head ， 删除所有重复的元素，使每个元素只出现一次 。返回 已排序的链表 。
 *
 * @Author Mr Wu yewen.wu.china@gmail.com
 */
public class Topic083 {

    public static void main(String[] args) {
        ListNode listNode = null;
        for(int i=7; i > 1; i--) {
            ListNode listNodeNew = new ListNode(2 * i);
            listNodeNew.next = listNode;
            listNode = listNodeNew;

            ListNode listNodeNew1 = new ListNode(2 * i);
            listNodeNew1.next = listNode;
            listNode = listNodeNew1;
        }

//        ListNode listNode1 = deleteDuplicates1(listNode);
        ListNode listNode2 = deleteDuplicates(listNode);
        System.out.println("end");
    }

    /**
     * 迭代
     * @param head
     * @return
     */
    public static ListNode deleteDuplicates1(ListNode head) {
        ListNode result = head;

        while(head!=null && head.next!=null) {
            if(head.val == head.next.val) {
                head.next = head.next.next;
                continue;
            }
            head = head.next;
        }
        return result;

    }

    /**
     * 官方
     * @param head
     * @return
     */
    public static ListNode deleteDuplicates2(ListNode head) {
        if (head == null) {
            return head;
        }

        ListNode cur = head;
        while (cur.next != null) {
            if (cur.val == cur.next.val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }

        return head;

    }

    /**
     * 递归
     * @param head
     * @return
     */
    public static ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        if (head.val == head.next.val) {
            head = deleteDuplicates(head.next);
        } else {
            head.next = deleteDuplicates(head.next);
        }
        return head;

    }


}
